import {
  request
} from '../../api/index'

import {
  MOLDING,
  inputValidHandle
} from '../../utils/valid'
const app = getApp();

const form = {
  formingPressure: {
    type: '成型压力',
    value: '',
    err: '',
    desc: MOLDING['formingPressure'].unit
  },
  formingSpeed: {
    type: '成型速度',
    value: '',
    err: '',
    desc: MOLDING['formingSpeed'].unit
  },
  // pressNumber: {
  //   type: '压机编号',
  //   value: ''
  // },
  powderMoisture: {
    type: '粉料水分',
    value: '',
    err: '',
    desc: MOLDING['powderMoisture'].unit
  },
  pressSpecifications: {
    type: '压机规格',
    value: '',
    err: '',
    pass:MOLDING['pressSpecifications'].pass,
    desc: MOLDING['pressSpecifications'].unit
  },
  specifications: {
    type: '坯体规格',
    value: '',
    err: '',
    desc: MOLDING['specifications']?.unit
  }
}
Page({

  /**
   * 页面的初始数据
   */
  data: {

    form,
    fields: Object.keys(form),
    canNext: false,
    id: '',
    group: [],
    groupId: '',
    recordState: app.globalData.editState,
    errs: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    this.setPageProperty(options);
    this.fetchData();

  },

  /**
   * 设置页面属性
   */
  setPageProperty(options) {
    this.setData({
      id: options.id,
      fromNavigation: options.navigation || 0,
      recordState: app.globalData.editState
    })
    wx.setNavigationBarTitle({
      title: '3-坯体成型'
    })
  },
  setGroup() {
    const obj = {};
    this.data.fields.forEach(it => {
      obj[it] = {
        err: '',
        value: form[it].value
      }
    })

    this.setData({
      group: [...this.data.group, obj]
    })
  },
  setValue(event) {
    const {
      i,
      field
    } = event.currentTarget.dataset,
      value = event.detail;
    let data = [...this.data.group];
    data[i][field]['value'] = value;
    this.setData({
      group: data
    })
  },
  onInput(event) {
    const key = event.currentTarget.dataset.key,
      value = event.detail,
      i = event.currentTarget.dataset.i,

      group = this.data.group,
      target = MOLDING[key];

    if (inputValidHandle(value, MOLDING, key) === false) {
      group[i][key]['err'] = '数值不正确：' + target.desc;

    } else {
      group[i][key]['err'] = '';
    }
    group[i][key]['value'] = String(value);
    this.setData({
      group
    })

  },
  onDelete(event) {
    const {
      i
    } = event.currentTarget.dataset;
    let data = [...this.data.group];
    data.splice(i, 1);
    this.setData({
      group: data
    })
  },
  onExpand(event) {
    const i = event.currentTarget.dataset.i;
    const dataSource = [...this.data.group];
    dataSource[i].display = !dataSource[i].display;
    this.setData({
      group: dataSource
    })
  },
  onChange() {
    if (this.data.group.length > 0) {
      const data = this.data.group.concat([]);
      let valid = true;
      data.map(it => {
        for (let k of Object.keys(it)) {
          if (!(it[k] || it[k]['value'])) {
            valid = false;
            wx.showToast({
              title: '存在未填写项目',
              icon: 'none'
            })
            break;
          } else if (it[k]['err']) {
            valid = false;
            wx.showToast({
              title: '存在不符合要求的数据',
              icon: 'none'
            })
            break;
          }
        }
      })
      if (valid) {
        let canNext = true;
        const pressDatum = this.data.group.map((it, index) => {
          delete it.display;
          for (let k of Object.keys(it)) {
            it[k] = JSON.stringify(it[k])
          }
          return {
            ...it,
            pressNumber: `\{\"value\":\"压机${index+1}\"\,\"err\":\"\"}`
          }
        })
        canNext && request.formingAdd(Object.assign({
          collectionRecordId: this.data.id,
          pressDatum,
        }, {
          id: this.data.groupId || null
        }, {
          number: pressDatum.length
        }), this.nextHandle)
      }
    } else {
      wx.showToast({
        title: '请先添加压机',
        icon: 'error'
      })
    }
  },
  nextHandle() {
    if (this.data.fromNavigation > 0) {
      wx.navigateBack({
        delta: 1
      })
      return
    }
  },
  fetchData() {
    request.formingList({
      collectionRecordIds: this.data.id
    }, (e) => {
      let data = JSON.parse(JSON.stringify(e[0]?.pressDatum || []))
      data.forEach(it => {
        Object.keys(it).map(item => {
          let par;
          try {
            let p = JSON.parse(it[item]);
            par = p instanceof Object ? p : par = {
              value: it[item],
              err: ''
            };
          } catch (e) {
            console.log("111", e)
            par = {
              value: it[item],
              err: ''
            }
          }
          it[item] = par;
        })
      })
      console.log(data)
      e[0]?.pressDatum ? this.setData({
        group: data,
        groupId: e[0].id
      }) : this.setGroup();
    })
  },
  onAdd() {
    this.setGroup();
  },
  onMius() {
    const data = [...this.data.group];
    data.pop();
    this.setData({
      group: data
    })
  },
  toHome() {
    wx.navigateBack({
      delta: 5
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})